-- ***************************************************************************************************
-- SELECT INCREMENTAL INSERT Stored Procedures for the list of tables mentioned in the Initialize file
--------------------------------------------------------------------------------------------------

--TABLE NAME: OrderDetail    STORED PROCEDURE NAME: Sales.sync_sp_OrderDetail_SelectIncrementalInserts

use [SyncSamplesDb_ChangeTracking_Custom]

if object_id(N'Sales.sync_sp_OrderDetail_SelectIncrementalInserts', 'P') is not null
	drop procedure Sales.sync_sp_OrderDetail_SelectIncrementalInserts
GO	
		create procedure Sales.sync_sp_OrderDetail_SelectIncrementalInserts (	
		@sync_last_received_anchor bigint, 
		@sync_new_received_anchor bigint, 
		@sync_initialized bit,
		@sync_client_id_binary varbinary)
AS
	IF (@sync_initialized = 0) 
	BEGIN
			SELECT		E.OrderDetailId
						, E.OrderId
						, E.Product
						, E.Quantity
			FROM		[SyncSamplesDb_ChangeTracking_Custom].[Sales].[OrderDetail] AS E
			LEFT JOIN	CHANGETABLE(CHANGES [SyncSamplesDb_ChangeTracking_Custom].[Sales].[OrderDetail], @sync_last_received_anchor) AS CT
						ON E.OrderDetailId = CT.OrderDetailId
						AND E.OrderId = CT.OrderId
			WHERE		CT.SYS_CHANGE_CONTEXT IS NULL 
						OR CT.SYS_CHANGE_CONTEXT <> @sync_client_id_binary
	END
		ELSE  
	BEGIN 
			SELECT		E.OrderDetailId
						, E.OrderId
						, E.Product
						, E.Quantity
			FROM		[SyncSamplesDb_ChangeTracking_Custom].[Sales].[OrderDetail] AS E
			JOIN		CHANGETABLE(CHANGES [SyncSamplesDb_ChangeTracking_Custom].[Sales].[OrderDetail], @sync_last_received_anchor) AS CT
						ON E.OrderDetailId = CT.OrderDetailId
						AND E.OrderId = CT.OrderId
			WHERE		CT.SYS_CHANGE_CREATION_VERSION <= @sync_new_received_anchor
						AND CT.SYS_CHANGE_OPERATION = 'I'
						AND (CT.SYS_CHANGE_CONTEXT IS NULL 
							OR CT.SYS_CHANGE_CONTEXT <> @sync_client_id_binary)
	END
GO 	
-------------------------------------------END------------------------------------------------------------------
